package org.xiaohanghu.starter;

import java.io.IOException;
import java.net.URISyntaxException;

/**
 * 帮助加载类文件，启动指定的main函数
 * 
 * @author xiaohanghu
 */
public class Main {

	public static final String START_CONFIG_PROPERTY_NAME = "xiaohanghu.start.config";
	public static final String START_HOME_PROPERTY_NAME = "xiaohanghu.start.home";

	public static final String DEFAULT_CONFIG_NAME = "start.properties";

	public static Logger log = Logger.getLogger();

	public static void main(String[] args) {
		String startHome = System.getProperty(START_HOME_PROPERTY_NAME);
		startHome = StringUtils.trimToNull(startHome);
		if (null == startHome) {
			try {
				startHome = PathUtils.getStartJarDir();
			} catch (URISyntaxException e) {
				log.error("Can't get default home throws "
						+ e.getClass().getName() + "!", e);
				return;
			} catch (IOException e) {
				log.error("Can't get default home throws "
						+ e.getClass().getName() + "!", e);
				return;
			}
		}
		String configPath = System.getProperty(START_CONFIG_PROPERTY_NAME);
		configPath = StringUtils.trimToNull(configPath);
		if (null == configPath) {
			configPath = startHome + DEFAULT_CONFIG_NAME;
		}

		try {
			start(configPath, startHome, args);
		} catch (Exception e) {
			log.error("Thorws" + e.getClass().getName() + " exception!", e);
		}
	}

	public static void start(String configPath, String startHome, String[] args)
			throws Exception {

		StartConfig config = StartConfigFactory.createStartConfig(configPath,
				startHome);

		config.addArguments(args);
		config.addSystemProperty(START_HOME_PROPERTY_NAME, startHome);
		config.addSystemProperty(START_CONFIG_PROPERTY_NAME, configPath);
		
		MainStarter start = new MainStarter();
		start.start(config);

	}

}
